package controllers

import (
	"fmt"
	"github.com/gofiber/fiber/v2"
	"log"
	"main/src/utils"
	"os"
	"strings"
)

func GitUpdate(c *fiber.Ctx) error {
	gitDirs := utils.FindGitDirectories(os.Getenv("SS_StaticDir"))
	repo := c.AllParams()["repo"]

	if len(gitDirs) == 0 {
		return c.Status(fiber.StatusPreconditionFailed).JSON(fiber.Map{
			"error": "No active .git directories",
		})
	}

	for _, dir := range gitDirs {
		if strings.Contains(dir, repo) {
			type Repo struct {
				FullName string `json:"fullName"`
			}
			type Pusher struct {
				Name string `json:"name"`
			}
			body := struct {
				TotalCommits int    `json:"totalCommits"`
				Repository   Repo   `json:"repository"`
				Pusher       Pusher `json:"pusher"`
			}{}
			if err := c.BodyParser(&body); err != nil {
				return err
			}
			log.Printf(`Remote repository %s updated
				Info:
					TotalCommits: %d
					PusherName: %s
				`, body.Repository.FullName, body.TotalCommits, body.Pusher.Name)

			err := utils.UpdateGitRepo(dir)
			if err != nil {
				log.Println(err)
			}
			return c.JSON(fiber.Map{
				"Repository": fmt.Sprintf("Repository %s found", repo),
			})
		}
	}

	return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
		"error": fmt.Sprintf("Repository %s not found", repo),
	})

}
